

package com.sunny.gateway.pms;

import com.sunny.gateway.dto.AuthResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 接口权限判断工具类
 *
 * @author sunny
 * @date 2025/05/31
 */
@Slf4j
@Component(value = "pms")
public class PermissionService {

	public static String USER_KEY = "user";

	/**
	 * 判断用户是否有指定的权限
	 * @param permission 权限字符串
	 * @return 是否有权限
	 */
	public Mono<Boolean> hasPermission(String permission) {
		return Mono.deferContextual(context -> {
            AuthResult.PigUser pigUser = context.get(USER_KEY);
            if (pigUser == null) {
                return Mono.just(false);
            }
            var authorities = pigUser.getAuthorities();
            return Mono.just(authorities.stream().map(AuthResult.PigUser.Authority::getAuthority)
                    .filter(StringUtils::hasText)
                    .anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x)));
        }).onErrorResume(e->{
			return Mono.empty();
		});
	}



}
